package com.sugar.psych.assessment.module.business.service.medal;

import cn.hutool.core.collection.CollUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import com.sugar.psych.assessment.module.business.controller.admin.medal.vo.*;
import com.sugar.psych.assessment.module.business.dal.dataobject.medal.MedalDO;
import com.sugar.psych.assessment.framework.common.pojo.PageResult;
import com.sugar.psych.assessment.framework.common.pojo.PageParam;
import com.sugar.psych.assessment.framework.common.util.object.BeanUtils;

import com.sugar.psych.assessment.module.business.dal.mysql.medal.MedalMapper;

import static com.sugar.psych.assessment.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.sugar.psych.assessment.framework.common.util.collection.CollectionUtils.convertList;
import static com.sugar.psych.assessment.framework.common.util.collection.CollectionUtils.diffList;
import static com.sugar.psych.assessment.module.business.enums.ErrorCodeConstants.*;

/**
 * 勋章信息 Service 实现类
 *
 * @author Ysugar
 */
@Service
@Validated
public class MedalServiceImpl implements MedalService {

    @Resource
    private MedalMapper medalMapper;

    @Override
    public Long createMedal(MedalSaveReqVO createReqVO) {
        // 插入
        MedalDO medal = BeanUtils.toBean(createReqVO, MedalDO.class);
        medalMapper.insert(medal);
        // 返回
        return medal.getId();
    }

    @Override
    public void updateMedal(MedalSaveReqVO updateReqVO) {
        // 校验存在
        validateMedalExists(updateReqVO.getId());
        // 更新
        MedalDO updateObj = BeanUtils.toBean(updateReqVO, MedalDO.class);
        medalMapper.updateById(updateObj);
    }

    @Override
    public void deleteMedal(Long id) {
        // 校验存在
        validateMedalExists(id);
        // 删除
        medalMapper.deleteById(id);
    }

    @Override
        public void deleteMedalListByIds(List<Long> ids) {
        // 校验存在
        validateMedalExists(ids);
        // 删除
        medalMapper.deleteByIds(ids);
        }

    private void validateMedalExists(List<Long> ids) {
        List<MedalDO> list = medalMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(MEDAL_NOT_EXISTS);
        }
    }

    private void validateMedalExists(Long id) {
        if (medalMapper.selectById(id) == null) {
            throw exception(MEDAL_NOT_EXISTS);
        }
    }

    @Override
    public MedalDO getMedal(Long id) {
        return medalMapper.selectById(id);
    }

    @Override
    public PageResult<MedalDO> getMedalPage(MedalPageReqVO pageReqVO) {
        return medalMapper.selectPage(pageReqVO);
    }

}